package com.jwgf.fault;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.jwgf.common.AppContext;

public class SaxFaultParse implements IXmlParse {

	@Override
	public HashMap<Integer, FaultContent> getFaultMapByParseXml(InputStream is)
			throws Exception {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		SaxHandler handler = new SaxHandler();
		parser.parse(is, handler);

		return handler.getFaultMap();
	}

	private class SaxHandler extends DefaultHandler {
		String current;
		HashMap<Integer, FaultContent> faultMap;
		int key;
		String value;
		int drawable_id = 0;
		String detail = null;

		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
			faultMap = new HashMap<Integer, FaultContent>();
		}

		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			if ("Fault".equals(localName)) {
				key = 0;
				value = null;
				drawable_id = 0;
				detail = null;
			} else if ("code".equals(localName) || "value".equals(localName)
					|| "drawable".equals(localName)
					|| "detail".equals(localName)) {
				current = localName;
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			super.endElement(uri, localName, qName);
			if ("Fault".equals(localName)) {
				faultMap.put(key, new FaultContent(value, detail, drawable_id));
			} else if ("code".equals(localName) || "value".equals(localName)
					|| "drawable".equals(localName)
					|| "detail".equals(localName)) {
				current = null;
			}
		}

		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			super.characters(ch, start, length);
			String s = new String(ch, start, length);
			if ("code".equals(current)) {
				key = Integer.parseInt(s, 16);
			} else if ("value".equals(current)) {
				value = s;
			} else if ("drawable".equals(current)) {
				drawable_id = AppContext
						.getInstance()
						.getResources()
						.getIdentifier(s, "drawable",
								AppContext.getInstance().getPackageName());
			} else if ("detail".equals(current)) {
				detail = s;
			}
		}

		public HashMap<Integer, FaultContent> getFaultMap() {
			return faultMap;
		}

	}

}
